<template>
  <!-- 首页主容器 -->
  <view class="index-container">
    <!-- 地图容器，包含地图和控制按钮 -->
    <view class="map-container">
      <!-- 顶部POI搜索组件 -->
      <POISearch 
        class="floating-search"
        :customPOIs="customPOIs" 
        @select-poi="handleSelectPOI"
        @search-complete="handleSearchComplete"
      />
      
      <MapContainer 
        ref="mapContainer" 
        :show-poi-markers="showPOIMarkers" 
        :show-add-button="true"
        @add-poi="handleAddPOI"
        @position-click="handlePositionClick"
      />
      
      <!-- 左上角工具按钮区 -->
      <view class="left-top-tools">
      
        <!-- 2D/3D视图切换按钮 -->
        <view class="tool-btn" @click="toggleViewMode">
          <view class="icon-svg" v-html="current3DMode ? icons.view3d : icons.view2d"></view>
        </view>
        <!-- 定位按钮，用于定位到用户当前位置 -->
        <view class="tool-btn" @click="locateCurrentPosition">
          <view class="icon-svg" v-html="icons.locate"></view>
        </view>
        <!-- POI标记显示开关 -->
        <view class="tool-btn" :class="{'poi-active': showPOIMarkers}" @click="togglePOIMarkers">
          <view class="icon-svg" v-html="icons.location"></view>
        </view>
      </view>
      
      <!-- 搜索结果标记层 -->
      <view class="search-result-marker" v-if="selectedPOI">
        <view class="marker-content">
          <text class="marker-name">{{ selectedPOI.name }}</text>
          <text class="marker-address">{{ selectedPOI.address }}</text>
          <view class="marker-actions">
            <button class="action-btn" @click="navigateToDetail">查看详情</button>
            <button class="action-btn" @click="navigateToHere">到这里去</button>
          </view>
        </view>
      </view>
    </view>
    <!-- 新增：AI客服悬浮按钮 -->
    <view class="ai-customer-btn" @click="showAIChat = true">
      <svg class="ai-customer-img" width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
        <circle cx="20" cy="20" r="20" fill="#3F7BFC"/>
        <rect x="10" y="14" width="20" height="12" rx="6" fill="#fff"/>
        <ellipse cx="16" cy="20" rx="2" ry="2.5" fill="#3F7BFC"/>
        <ellipse cx="24" cy="20" rx="2" ry="2.5" fill="#3F7BFC"/>
        <rect x="15" y="24" width="10" height="2" rx="1" fill="#3F7BFC"/>
        <rect x="8" y="12" width="4" height="4" rx="2" fill="#FFB300"/>
        <rect x="28" y="12" width="4" height="4" rx="2" fill="#FFB300"/>
      </svg>
    </view>
    <!-- 新增：AIChat 组件弹窗 -->
    <AIChat :visible="showAIChat" :popupOpacity="0.92" @close="showAIChat = false" @play-bot-audio="playTTS" />
  </view>
</template>


<script>
// 引入高德地图基础组件
import MapContainer from '@/components/MapContainer.vue';
// 引入POI搜索组件
import POISearch from '@/components/POISearch.vue';
// 引入SVG图标，修正导入路径
import { generalIcons } from '@/static/icons/icon-svg.js';
import { usePOIStore } from '@/store/poiStore';
import { useFacilityStore } from '@/store/facilityStore';
import AIChat from '@/components/AIChat.vue';

export default {
  // 注册使用的组件
  components: {
    MapContainer,     // 基础地图组件
    POISearch,        // POI搜索组件
    AIChat            // 注册AIChat组件
  },
  
  // 页面数据
  data() {
    return {
      current3DMode: false, // 当前是否为3D模式
      icons: generalIcons,   // 通用图标
      showPOIMarkers: false, // 是否显示POI标记
      customPOIs: [],        // 自定义POI列表
      searchResults: [],     // 搜索结果
      selectedPOI: null,     // 当前选中的POI
      showAIChat: false      // 控制AIChat显示隐藏
    }
  },
  
  // 页面加载时执行
  onLoad() {
    // 页面初始化逻辑
    console.log('首页组件已加载');
    
    // 初始化POI和设施数据
    const poiStore = usePOIStore();
    poiStore.initPOIs();
    this.customPOIs = poiStore.getAllPOIs;
    
    const facilityStore = useFacilityStore();
    facilityStore.loadFacilitiesFromStorage();
    
    // 合并设施信息到自定义POI列表
    const facilities = facilityStore.getAllFacilities;
    if (facilities && facilities.length) {
      const facilityPOIs = facilities.map(facility => ({
        id: facility.id || `facility-${Date.now()}`,
        name: facility.name,
        address: facility.address || '未知地址',
        location: facility.position,
        type: 'facility',
        isCustom: true
      }));
      this.customPOIs = [...this.customPOIs, ...facilityPOIs];
    }
  },

  // 页面就绪时执行
  onReady() {
    console.log('首页组件已就绪，DOM已渲染');
  },
  
  // 页面方法
  methods: {
    // 处理POI搜索完成事件
    handleSearchComplete(results) {
      console.log('搜索完成，结果数:', results.length);
      this.searchResults = results;
    },
    
    // 处理POI选择事件
    handleSelectPOI(poi) {
      console.log('选择了POI:', poi);
      this.selectedPOI = poi;
      
      // 如果地图组件已加载，移动到选中的POI位置
      if (this.$refs.mapContainer && this.$refs.mapContainer.map && poi.location) {
        this.$refs.mapContainer.map.setCenter([poi.location.lng, poi.location.lat]);
        this.$refs.mapContainer.map.setZoom(15); // 设置合适的缩放级别
      }
    },
    
    // 导航到POI详情页
    navigateToDetail() {
      if (!this.selectedPOI) return;
      
      // 根据POI类型决定跳转到哪个页面
      if (this.selectedPOI.type === 'facility') {
        uni.navigateTo({
          url: `/pages/facility/detail?id=${this.selectedPOI.id}`
        });
      } else {
        // 保存POI信息到本地以便详情页使用
        uni.setStorageSync('selected_poi', JSON.stringify(this.selectedPOI));
        uni.navigateTo({
          url: '/pages/map/poi-detail'
        });
      }
    },
    
    // 导航功能
    navigateToHere() {
      if (!this.selectedPOI || !this.selectedPOI.location) {
        uni.showToast({
          title: '无法获取位置信息',
          icon: 'none'
        });
        return;
      }
      
      const location = this.selectedPOI.location;
      uni.openLocation({
        latitude: location.lat,
        longitude: location.lng,
        name: this.selectedPOI.name,
        address: this.selectedPOI.address,
        success: () => {
          console.log('打开导航成功');
        },
        fail: (err) => {
          console.error('打开导航失败:', err);
          uni.showToast({
            title: '打开导航失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 切换地图视图模式
    toggleViewMode() {
      this.current3DMode = !this.current3DMode;
      console.log('切换视图模式');
    },
    
    // 定位到当前位置
    locateCurrentPosition() {
      // 调用定位功能
      console.log('定位到当前位置');
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          // 将地图中心移动到当前位置
          if (this.$refs.mapContainer && this.$refs.mapContainer.map) {
            this.$refs.mapContainer.map.setCenter([res.longitude, res.latitude]);
          }
        },
        fail: () => {
          uni.showToast({
            title: '无法获取当前位置',
            icon: 'none'
          });
        }
      });
    },
    
    // 切换POI标记显示
    togglePOIMarkers() {
      this.showPOIMarkers = !this.showPOIMarkers;
      uni.showToast({
        title: this.showPOIMarkers ? 'POI标记已显示' : 'POI标记已隐藏',
        icon: 'none',
        duration: 1500
      });
    },
    
    // 处理地图位置点击事件
    handlePositionClick(position) {
      console.log('点击了地图位置:', position);
    },
    
    // 处理添加POI的事件
    handleAddPOI(position) {
      console.log('添加POI，位置:', position);
      
      // 检查位置数据有效性
      if (!position || isNaN(position.lat) || isNaN(position.lng)) {
        uni.showToast({
          title: '位置数据无效，请重试',
          icon: 'none'
        });
        return;
      }
      
      // 格式化经纬度，避免NaN
      const lat = isNaN(position.lat) ? 0 : parseFloat(position.lat.toFixed(6));
      const lng = isNaN(position.lng) ? 0 : parseFloat(position.lng.toFixed(6));
      
      // 将位置信息保存到临时存储
      try {
        const validPosition = { 
          lat: lat,
          lng: lng
        };
        uni.setStorageSync('temp_facility_position', JSON.stringify(validPosition));
      } catch (e) {
        console.error('保存临时位置数据失败:', e);
      }
      
      // 跳转到设施添加页面，传递有效的经纬度参数
      uni.navigateTo({
        url: `/pages/facility/add?lat=${lat}&lng=${lng}`
      });
    },
    // 新增：TTS语音合成并播放
    playTTS(text) {
      uniCloud.callFunction({
        name: 'ttsProxy',
        data: { text },
        success: (res) => {
          console.log('TTS返回：', res);
          if (res.result && res.result.data) {
            this.playBase64PCM(res.result.data);
          } else {
            console.error('TTS返回数据为空或格式异常', res);
            uni.showToast({ title: 'TTS无音频数据', icon: 'none' });
          }
        },
        fail: (err) => {
          uni.showToast({ title: '语音合成失败', icon: 'none' });
          console.error('TTS调用失败', err);
        }
      });
    },
    // 新增：base64 PCM转WAV并播放
    playBase64PCM(base64Str) {
      if (!base64Str) {
        console.error('base64音频数据为空');
        uni.showToast({ title: '音频数据为空', icon: 'none' });
        return;
      }
      function base64ToArrayBuffer(base64) {
        const binary = atob(base64);
        const len = binary.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
          bytes[i] = binary.charCodeAt(i);
        }
        return bytes.buffer;
      }
      const pcmArrayBuffer = base64ToArrayBuffer(base64Str);
      console.log('PCM数据长度:', pcmArrayBuffer.byteLength);
      function encodeWAV(pcm, sampleRate = 24000, numChannels = 1, bitDepth = 16) {
        const bytesPerSample = bitDepth / 8;
        const blockAlign = numChannels * bytesPerSample;
        const buffer = new ArrayBuffer(44 + pcm.byteLength);
        const view = new DataView(buffer);
        function writeString(view, offset, string) {
          for (let i = 0; i < string.length; i++) {
            view.setUint8(offset + i, string.charCodeAt(i));
          }
        }
        writeString(view, 0, 'RIFF');
        view.setUint32(4, 36 + pcm.byteLength, true);
        writeString(view, 8, 'WAVE');
        writeString(view, 12, 'fmt ');
        view.setUint32(16, 16, true);
        view.setUint16(20, 1, true);
        view.setUint16(22, numChannels, true);
        view.setUint32(24, sampleRate, true);
        view.setUint32(28, sampleRate * blockAlign, true);
        view.setUint16(32, blockAlign, true);
        view.setUint16(34, bitDepth, true);
        writeString(view, 36, 'data');
        view.setUint32(40, pcm.byteLength, true);
        new Uint8Array(buffer, 44).set(new Uint8Array(pcm));
        return buffer;
      }
      const wavBuffer = encodeWAV(pcmArrayBuffer);
      const blob = new Blob([wavBuffer], { type: 'audio/wav' });
      const url = URL.createObjectURL(blob);
      console.log('音频URL:', url);
      const audio = new Audio(url);
      audio.onplay = () => { console.log('音频开始播放'); };
      audio.onended = () => { console.log('音频播放结束'); };
      audio.onerror = (e) => { console.error('音频播放出错', e); };
      audio.play();
    }
  },
  watch: {
    showAIChat(val) {
      if (val) {
        // AI客服弹窗打开时自动播报欢迎语
        this.playTTS('您好，我是蓝心大模型智能客服，有什么可以帮您？');
      }
    }
  }
}
</script>

<style>
/* 全局样式，禁用滚动和隐藏滚动条，但保留必要的overflow设置 */
page {
  overflow: hidden;
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
}

/* 隐藏所有可能的滚动条 */
::-webkit-scrollbar {
  display: none;
  width: 0 !important;
  height: 0 !important;
  background: transparent;
  -webkit-appearance: none;
}

/* 通用滚动条隐藏 */
* {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 首页容器样式 */
.index-container {
  width: 100%;
  height: 100vh;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 地图容器样式 */
.map-container {
  width: 100%;
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
}

/* 浮动搜索框样式 */
.floating-search {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 200;
}

/* 左上角工具按钮容器 */
.left-top-tools {
  position: fixed;
  left: 20rpx;
  top: 120rpx; /* 调整顶部距离，为浮动搜索框留出空间 */
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 99;
}

/* 左上角按钮之间的间距 - 修改为垂直方向的间距 */
.left-top-tools .tool-btn {
  margin-right: 0;
  margin-bottom: 20rpx; /* 垂直间距 */
  z-index:999;
}

/* 工具按钮样式 */
.tool-btn {
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 50%;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.2s ease;
  transform: scale(1);
  z-index:999;
}

.tool-btn:active {
  transform: scale(0.92);
  background-color: rgba(245, 245, 245, 0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 图标SVG容器 */
.icon-svg {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-svg svg {
  width: 20px;
  height: 20px;
}

/* POI按钮激活状态 */
.poi-active {
  background-color: #3F7BFC;
}

.poi-active .icon-svg {
  color: white;
}

/* 搜索结果标记样式 */
.search-result-marker {
  position: absolute;
  left: 50%;
  bottom: 30rpx;
  transform: translateX(-50%);
  width: 90%;
  background-color: white;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.15);
  padding: 24rpx;
  z-index: 100;
}

.marker-content {
  display: flex;
  flex-direction: column;
}

.marker-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.marker-address {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.marker-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 16rpx;
}

.action-btn {
  flex: 1;
  margin: 0 10rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  border-radius: 35rpx;
  background: linear-gradient(135deg, #4B89FD, #3F7BFC);
  color: white;
  border: none;
}

.action-btn:first-child {
  margin-left: 0;
  background: #f5f5f5;
  color: #333;
}

.action-btn:last-child {
  margin-right: 0;
}

/* AI客服悬浮按钮样式 */
.ai-customer-btn {
  position: fixed;
  right: 15px;
  bottom: 60px;
  width: 64px;
  height: 64px;
  background: rgba(255,255,255,0.85);
  border-radius: 50%;
  box-shadow: 0 4px 16px rgba(63,123,252,0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10000;
  transition: box-shadow 0.2s;
}
.ai-customer-btn:hover {
  box-shadow: 0 8px 32px rgba(63,123,252,0.25);
}
.ai-customer-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  z-index:20001;
}
</style>
